
package com.example.partner.fragment;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.partner.R;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import android.widget.ListView;
import android.widget.Toast;

import com.example.partner.activity.home.UserInfoActivity;
import com.example.partner.adapter.user.UserAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.common.UserInfoViewModel;
import com.example.partner.model.domain.User;
import com.example.partner.model.vo.UserVo;
import com.example.partner.service.FollowService;

import org.modelmapper.ModelMapper;

import java.util.List;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class CommonConcernFragment extends Fragment {
    private FollowService followService;
    UserAdapter adapter;
    ListView listView;
    Long userId,loginUserId;
    private UserInfoViewModel viewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件
        if (getArguments() != null) {
            userId = getArguments().getLong("userId");
        }
        return inflater.inflate(R.layout.fragment_common_conern, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 在这里初始化 UI 组件
        listView = view.findViewById(R.id.userList);
        // 初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) // 替换为您的服务器地址
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        followService = retrofit.create(FollowService.class);
        viewModel = new ViewModelProvider(requireActivity()).get(UserInfoViewModel.class);
        userId = viewModel.getUserId();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);
        loginUserId = sharedPreferences.getLong("userId", -1);
        followCommons(userId,loginUserId);
        listView.setOnItemClickListener((adapterView, listview, position, l) -> {
            // 获取点击的项
            User selectedUser = (User) adapter.getItem(position);
            String userAccount = selectedUser.getUserAccount();
            String username = selectedUser.getUsername();
            String avatarUrl = selectedUser.getAvatarUrl();
            Long selectedUserId = selectedUser.getId();
            // 创建Intent并启动新的Activity
            Intent intent = new Intent(getContext(), UserInfoActivity.class);
            intent.putExtra("username", username);
            intent.putExtra("userAccount",userAccount);
            intent.putExtra("avatarUrl",avatarUrl);
            intent.putExtra("selectedUserId",selectedUserId);
            startActivity(intent);
        });
    }

    private void followCommons(Long userId,Long loginUserId) {
        followService.followCommons(userId,loginUserId).enqueue(new Callback<BaseResponse<List<UserVo>>>() {
            @Override
            public void onResponse(Call<BaseResponse<List<UserVo>>> call, Response<BaseResponse<List<UserVo>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    ModelMapper modelMapper = new ModelMapper();
                    List<UserVo> userVos = response.body().getData();
                    if (userVos == null){
                        Toast.makeText(getContext(), "无共同关注", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        List<User> userList = userVos.stream()
                                .map(userVo -> modelMapper.map(userVo, User.class))
                                .collect(Collectors.toList());
                        adapter = new UserAdapter(getContext(), userList);
                        listView.setAdapter(adapter);
                    }
                    // 更新UI或处理数据
                } else {
                    // 处理错误情况
                    Toast.makeText(getContext(), "请求错误", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(Call<BaseResponse<List<UserVo>>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }


}
